﻿#include<stdlib.h>

// 归并排序(时间复杂度O（n*logn)
void _MergeSort(int* arr, int left, int right, int* tem)
{
	//分解
	if (left >= right)
	{
		return;
	}
	int mid = (left + right) / 2;
	_MergeSort(arr, left, mid, tem);
	_MergeSort(arr, mid + 1, right, tem);

	//合并两个有序数组
	int begin1 = left;
	int begin2 = mid+1;
	int end1 = mid;
	int end2 = right;

	int index = left;
	while (begin1 <= end1 && begin2 <= end2)
	{
		if (arr[begin1] > arr[begin2])
		{
			tem[index++] = arr[begin2++];
		}
		else
		{
			tem[index++] = arr[begin1++];
		}
	}

	while (begin1 <= end1)
	{
		tem[index++] = arr[begin1++];
	}
	while (begin2 <= end2)
	{
		tem[index++] = arr[begin2++];
	}

	for (int i = left; i <= right; i++)
	{
		arr[i] = tem[i];
	}
}

void MergeSort(int* arr, int n)
{
	int* tem = (int*)malloc(sizeof(int) * n);
	_MergeSort(arr, 0, n - 1, tem);
	free(tem);
}
